package com.lecture.java8.multithreading.callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author luyn
 * @version 1.0
 * @description 实现callable接口创建线程
 * @date 2021/1/15 10:43
 */
public class CallableTest {
    public static void main(String[] args) {
        //3：创建callable接口实现类的对象
        NumCallable numCallable = new NumCallable();
        //4：将此callable实现类的对象作为参数传递到FutureTask构造器中
        FutureTask<Integer> futureTask = new FutureTask<>(numCallable);
        //：将futureTask对象作为参数传递到Thread中。并start/
        new Thread(futureTask).start();
        try {
            //：获取callable中的call方法的返回值。
            Integer o = futureTask.get();
            System.out.println(o);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

//1：创建一个实现callable接口的实现类
class NumCallable implements Callable<Integer> {

    //2：实现call方法，将此线程需要执行的操作声明在call中。
    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            if(i%2 ==0) {
                System.out.println("i=" + i);
                sum += i;
            }
        }
        return sum;
    }
}